/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include "storage_manager.h"
#include <mutex>
#include <map>
#include <atomic>
#include <thread>
#include <memory>
#include <vector>
#include <string>
#include "nlohmann/json.hpp"
#include "utils_noncopyable.h"
#include "utils_timer.h"

namespace El {
namespace Storage {

class StorageManagerImpl final : public IStorageManager {
    DISALLOW_COPY_AND_MOVE(StorageManagerImpl);

public:
    StorageManagerImpl();
    ~StorageManagerImpl() override;

    bool Start() override;

    void Stop() override;

    std::shared_ptr<IStorageDevice> GetDevice(std::string_view devicePath) override;

    bool RemoveDevice(std::string devicePath) override;

    StorageCapacity GetTotalCapacity() const override;

    bool CleanupSpace(uint64_t requiredBytes) override;

    uint32_t RegisterStorageEventCallback(StorageEventCallback callback) override;

    bool UnregisterStorageEventCallback(uint32_t callbackId) override;

    bool GetDefaultUdiskStatus(DeviceStatus &status) override;

private:
    void StartMonitoring();
    void StopMonitoring();
    void CheckCapacityWarnings();
    void EnumerateExistingDevices();
    void NotifyStorageEvent(const std::shared_ptr<IStorageDevice> &device, DeviceStatus status);
    DeviceType DetectDeviceType(const std::map<std::string, std::string> &properties, const std::string &devnode);
    bool AddAndMountDevice(const std::string &devpath, DeviceType deviceType);
    void RemoveDeviceInternal(const std::string &devpath);

private:
    mutable std::mutex devicesMutex_;
    std::map<std::string, std::shared_ptr<IStorageDevice>> devices_;
    std::map<std::string, bool> deviceWarningStates_;
    mutable std::mutex policyMutex_;
    nlohmann::json storageConfig_;
    std::string mountPath_;
    uint32_t warningThreshold_;
    uint32_t reserveSpace_;
    int32_t listenerId_;
    int32_t deviceMonitorHandle_{-1};  // DeviceMonitor回调句柄

    std::mutex callbackMutex_;
    std::map<uint32_t, StorageEventCallback> storageEventCallbacks_;
    uint32_t nextCallbackId_ = 1;

    // 容量监控定时器
    Utils::Timer capacityMonitorTimer_;
};

} // namespace Storage
} // namespace El
